import {login, logout, isLogin, authorization} from "@/api/user.js";
import {setToken, setUserInfo, removeToken, removeUserInfo} from "@/utils/auth.js";

const state = {
    user: {},
    isLogin: false,
};

const getters = {
    user: (state) => state.user,
    isLogin: (state) => state.isLogin,
    isSeller: (state) => {
        console.log("type",state.user.type)
        return state.user.type === "seller"
    }
};


const mutations = {
    logout(state) {
        state.isLogin = false;
        state.user = {};
        removeToken();
        removeUserInfo();
    },

    setUser(state, user) { //user={id,name}
        state.user = user;
    },

    setIsLogin(state, isLogin) {
        state.isLogin = isLogin;
    },

};

const actions = {
    async login(context, user) {
        let result = await login(user);
        if (result) {
            context.commit("setUser", result.data.user);
            context.commit("setIsLogin", true);

            setToken(result.data.token); //
            setUserInfo(result.data.user);
        }
        return result;
    },

    async islogin(context) {
        let result = await isLogin();
        if (result.state) {
            context.commit("setUser", result.data.user);
            context.commit("setIsLogin", true);

            setToken(result.data.token);
            setUserInfo(result.data.user);
        }
        return result;
    },

    async logout(context) {
        let result = await logout().catch(err => {
            this.$dialog({title: "退出失败", message: err.msg});
            err.state = false
            return err
        });
        if (result.state) {
            context.commit("logout")
        }
        return result;
    },

    async authorization() {
        let result = await authorization();
        if (result.code == 1) {
            setToken(result.data.token); // 重置token 即重置过期时间
        }
        return result;
    }

};


export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations,
};
